<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>WebChat</title>
        <link href="/static/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
        <link href="/static/font-awesome/css/font-awesome.css" type="text/css" rel="stylesheet" />
        <link href="/static/css/plugins/toastr/toastr.min.css" type="text/css" rel="stylesheet" />
        <link href="/static/css/animate.css" type="text/css" rel="stylesheet" />
        <link href="/static/css/style.css" type="text/css" rel="stylesheet" />
    </head>
    <body class="top-navigation">
        <div id="wrapper">
            <div id="page-wrapper" class="gray-bg">
                <div class="row border-bottom white-bg">
                    <nav class="navbar navbar-static-top" role="navigation">
                        <div class="navbar-header">
                            <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" class="navbar-toggle collapsed" type="button">
                                <i class="fa fa-reorder"></i>
                            </button>
                            <a href="#" class="navbar-brand">WebChat</a>
                        </div>
                        <div class="navbar-collapse collapse" id="navbar">
                            <ul class="nav navbar-top-links navbar-right">
                                <li>
                                    <span class="m-r-sm text-muted welcome-message">当前用户: {{ .user.Email }}</span>
                                </li>
                                <li>
                                    <a href={{ urlfor "UserController.Logout" }} class="a-logout">
                                        <i class="fa fa-sign-out"></i> 退出
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </nav>
                </div>
                <div class="wrapper-content">
                    <div class="ibox chat-view">
                        <div class="ibox-title">
                            <small class="pull-right text-muted"><span id="user_online"></span>位(在线) / <span id="user_total"></span>位(总数)</small>
                            聊天窗口
                        </div>
                        <div class="ibox-content">
                            <div class="row">
                                <div class="col-md-9 ">
                                    <div class="chat-discussion">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="chat-users">
                                        <div class="users-list">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-11">
                                    <div class="chat-message-form">
                                        <div class="form-group">
                                            <textarea class="form-control message-input" id="text-message" name="message"style="resize:none" placeholder="Ctrl + Enter发送"></textarea>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-1">
                                    <button type="button" id="btn-message" class="btn btn-lg btn-primary m-b" style="margin: 10px 10px 10px -10px; padding: 20px;">发送</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <audio id="notify" src="/static/audio/notify.ogg" preload></audio>
        <script type="text/javascript" src="/static/js/jquery-2.1.1.js"></script>
        <script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="/static/js/plugins/metisMenu/jquery.metisMenu.js"></script>
        <script type="text/javascript" src="/static/js/inspinia.js"></script>
        <script type="text/javascript" src="/static/js/plugins/pace/pace.min.js"></script>
        <script type="text/javascript" src="/static/js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
        <script type="text/javascript" src="/static/js/plugins/toastr/toastr.min.js"></script>
        <script type="text/javascript" src="/static/js/xss.js"></script>
        <script type="text/javascript">

            jQuery(document).ready(function() {
                toastr.options = {
                    "closeButton": true,
                    "debug": false,
                    "progressBar": true,
                    "positionClass": "toast-top-center",
                    "onclick": null,
                    "showDuration": "400",
                    "hideDuration": "1000",
                    "timeOut": "3000",
                    "extendedTimeOut": "1000",
                    "showEasing": "swing",
                    "hideEasing": "linear",
                    "showMethod": "fadeIn",
                    "hideMethod": "fadeOut"
                };

                var user = {{ .user.Id }};

                var tpl_msg = [
                                '<div class="chat-message #position#">',
                                '<img class="message-avatar" src="/static/img/avatar/a#pk#.jpg" alt=""/>',
                                '<div class="message">',
                                '<a class="message-author" href="javascript:void(0);">#user#</a>',
                                '<span class="message-date">#date#</span>',
                                '<span class="message-content">#msg#</span>',
                                '</div>',
                                '</div>'
                            ].join("");
                var tpl_user = [
                                '<div class="chat-user">',
                                '<span class="pull-right label label-#status#">#status_text#</span>',
                                '<img class="chat-avatar" src="/static/img//avatar/a#pk#.jpg" alt="" />',
                                '<div class="chat-user-name">',
                                '<a href="javascript:void(0);">#user#</a>',
                                '</div>',
                                '</div>'
                            ].join("");

                var reload = function() {
                    jQuery.get(
                        {{ urlfor ".UserController.List" }},
                        {_ : (new Date()).getTime()},
                        function(response) {
                            if(response['code'] == 400) {
                                alert("请进行登陆");
                                window.location.replace({{ urlfor "UserController.Login" }});
                            } else if(response['code'] == 200) {
                                var panel = jQuery('.users-list');
                                var contents = [];
                                var online = 0;
                                jQuery('#user_total').text(response['users'].length);
                                jQuery.each(response['users'], function(k, v) {
                                    if(v['online']) {
                                        online += 1;
                                    }
                                    var msg = tpl_user.replace(/#pk#/g, v['user']['id']);
                                    msg = msg.replace(/#user#/g, v['user']['email']);
                                    msg = msg.replace(/#status#/g, v['online'] ? 'primary' : 'warning');
                                    msg = msg.replace(/#status_text#/g, v['online'] ? '在线' : '离线');
                                    contents.push(msg);
                                });
                                jQuery('#user_online').text(online);
                                panel.html(contents.join(""));
                            }
                        },
                        "json"
                    );
                }

                var websocket = null;
                var get_websocket = function() {
                    var ws = new WebSocket("ws://" + window.location.host + "/ws/msg/");
                    ws.onerror = function() {
                        console.log("websocket连接错误");
                        websocket = null;
                    };

                    ws.onopen = function() {
                        reload();
                        console.log("WebSocket open");
                    };

                    ws.onmessage = function(e) {
                        console.log("msg:" + e.data);
                        try{
                            var json = jQuery.parseJSON(e.data);
                            if(json['code'] == 400) {
                                alert("请进行登陆");
                                window.location.replace({{ urlfor "UserController.Login" }});
                            } else if(json['code'] == 200) {
                                if(json['user'] && user !== json['user']['id']) {
                                    try {
                                        jQuery('#notify')[0].play();
                                    } catch(e) {
                                        console.log(e);
                                    }
                                }

                                switch(json['type']) {
                                    case 'online':
                                        if(user !== json['user']['id']) {
                                            toastr.clear();
                                            toastr['success']("用户" + HtmlEncode(json["user"]['email']) + "上线");
                                            reload();
                                        }
                                        break;
                                    case 'offline':
                                        if(user !== json['user']['id']) {
                                            toastr.clear();
                                            toastr['warning']("用户" + HtmlEncode(json["user"]['email']) + "下线");
                                            reload();
                                        }
                                        break;
                                    case 'msg':
                                        var msg = tpl_msg.replace(/#position#/g, user == json['user']['id'] ? 'right' : 'left');
                                        msg = msg.replace(/#user#/g, HtmlEncode(json['user']['email']));
                                        msg = msg.replace(/#pk#/g, json['user']['id']);
                                        msg = msg.replace(/#date#/g, HtmlEncode(json['date']));
                                        msg = msg.replace(/#msg#/g, HtmlEncode(json['msg']));
                                        var panel = jQuery('.chat-discussion');
                                        panel.append(msg);
                                        panel.scrollTop(panel[0].scrollHeight);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        } catch(e) {
                            console.log(e);
                        }
                    };

                    ws.onclose = function() {
                        console.log("websocket关闭连接");
                        websocket = null;
                    };
                    return ws;
                }

                websocket = get_websocket();

                jQuery("#btn-message").on("click", function() {
                    var msg = jQuery("#text-message").val();
                    msg = msg.replace(/(^\s*)|(\s*$)/g, "");
                    if(msg) {
                        if(websocket === null) {
                            websocket = get_websocket();
                            toastr.clear();
                            toastr['error']("websocket重新连接, 请重试");
                        }
                        if(websocket.readyState == WebSocket.OPEN){
                            jQuery("#text-message").val("");
                            websocket.send(JSON.stringify({"type": "msg", "msg": msg}));
                        }

                    }
                });

                jQuery(window).on('beforeunload', function() {
                    return '确定离开?';
                });

                jQuery(document).keydown(function(event) {
                    if(event['ctrlKey'] && event['keyCode'] === 13) {
                        jQuery("#btn-message").trigger("click");
                    }
                });
            });
        </script>
    </body>
</html>
